﻿const Pic = require('../model/pic.js');
const router = require('koa-router')();
const fs = require('fs');
const path = require('path');

//上传图片
router.all('/uploadPic', async (ctx) => {
  // 上传单个文件
  const file = ctx.request.files.file; // 获取上传文件
  // 创建可读流
  const reader = fs.createReadStream(file.path);
  let filePath = path.join(__dirname, '../../static/upload') + `/${file.name}`;
  // 创建可写流
  const upStream = fs.createWriteStream(filePath);
  // 可读流通过管道写入可写流
  reader.pipe(upStream);
  return ctx.body = {
    obj: file.name,
    path: filePath,
    code: 200
  };
})

//提交图片
router.post('/addPic', async (ctx) => {
  const picData = new Pic({
    username: ctx.request.body.username,
    pic: ctx.request.body.pic,
    path: ctx.request.body.path,
    create_time: ctx.request.body.create_time
  });
  await new Promise((resolve, reject) => {
    picData.save((err) => {
      if (err) {
        reject(err);
        ctx.body = {
          code: 500,
          obj: err
        };
      }
      resolve();
      ctx.body = {
        code: 200,
        obj: '添加成功'
      };
    });
  });
})
module.exports = router.routes();
